package com.example.myapplication.ui.slideshow;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.myapplication.R;
import com.example.myapplication.databinding.FragmentSlideshowBinding;

public class SlideshowFragment extends Fragment {
    private FragmentSlideshowBinding binding;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        SlideshowViewModel slideshowViewModel = new ViewModelProvider(this).get(SlideshowViewModel.class);

        binding = FragmentSlideshowBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        setupViews(root);
        return root;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void setupViews(View view) {
        // Set version info
        try {
            PackageInfo pInfo = requireContext().getPackageManager().getPackageInfo(
                    requireContext().getPackageName(), 0);
            TextView versionTextView = view.findViewById(R.id.app_version);
            versionTextView.setText(getString(R.string.version_format, pInfo.versionName));
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        // Set click listeners
        view.findViewById(R.id.privacy_policy_card).setOnClickListener(v -> openPrivacyPolicy());
        view.findViewById(R.id.terms_card).setOnClickListener(v -> openTermsOfService());
    }

    private void openPrivacyPolicy() {
        String url = getString(R.string.privacy_policy_url);
        openWebPage(url);
    }

    private void openTermsOfService() {
        String url = getString(R.string.terms_of_service_url);
        openWebPage(url);
    }

    private void openWebPage(String url) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(url));
        if (intent.resolveActivity(requireContext().getPackageManager()) != null) {
            startActivity(intent);
        } else {
            Toast.makeText(requireContext(), R.string.no_browser_error, Toast.LENGTH_SHORT).show();
        }
    }
}